package edu.cth.scrabbit.server.core;

import edu.cth.scrabbit.server.core.network.PlayerThread;
import edu.cth.scrabbit.shared.GameLetter;
import edu.cth.scrabbit.shared.Player;

/**
 * A class that contains the server's information about a player
 * 
 * @author Anders Jonsson, Marcus Harryson
 * 
 */
public class ServerPlayer extends Player implements IServerPlayer {
	private static final long serialVersionUID = 706958250585323745L;
	private transient PlayerThread playerThread;
	private transient GameLetter[] letters;

	// A ServerPlayer may not be created without a PlayerThread:
	private ServerPlayer() {
		// Empty private constructor
	}

	public ServerPlayer(PlayerThread thread) {
		super();
		this.playerThread = thread;
		this.letters = new GameLetter[7];
		for (int i = 0; i < letters.length; i++) {
			letters[i] = new GameLetter();
			// Fill it with dummies
		}
	}

	@Override
	public void giveLetter(GameLetter letter) {
		// First, find where we can put this letter:
		int index = -1;
		for (int i = 0; i < letters.length; i++) {
			if (letters[i].isDummy()) {
				index = i;
				break;
			}
		}
		if (index != -1) {
			letters[index] = letter;
		}
	}

	@Override
	public void removeLetter(GameLetter letter) {
		for (int i = 0; i < letters.length; i++) {
			if (!letters[i].isDummy() && letters[i].equals(letter)) {
				// Replace it with a dummy
				letters[i] = new GameLetter();
				return;
			}
		}
	}

	@Override
	public PlayerThread getThread() {
		return this.playerThread;
	}

	@Override
	public GameLetter[] getLetters() {
		return letters;
	}

	@Override
	public void setScore(int newScore) {
		this.score = newScore;
	}

	@Override
	public void givePoints(int newPoints) {
		this.score += newPoints;
	}

	@Override
	public Player toPlayer() {
		return new Player(name, position, score);
	}

}
